/*
 * Copyright        : Copyright (c) 2011 Hegaka
 * Author           : Jon Arrien
 * Twitter          : @jonarrien
 * All right reserved
 */


#import <QuartzCore/QuartzCore.h>
#import "GalleryButton.h"
#import "GalleryScrollView.h"

@implementation GalleryButton

@synthesize delegate;
@synthesize originalPosition = _originalPosition;
@synthesize mainView, scrollParent;

- (id)init
{
    self = [super init];
    if (self) {
        // Initialization code here.
    }

    return self;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self){

        isInScrollview	= YES;

        self.backgroundColor = [UIColor blackColor];
        self.layer.borderWidth = 2;
        self.layer.borderColor = [UIColor whiteColor].CGColor;
        self.layer.masksToBounds = YES;
        self.layer.cornerRadius = 7;
    }
    return self;
}


#pragma mark - DRAG AND DROP

-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    [self.delegate touchDown];
    self.originalPosition = self.center;
    self.scrollParent.scrollEnabled = NO;

	if (isInScrollview == YES) {
		CGPoint newLoc = CGPointZero;
        newLoc = [[self superview] convertPoint:self.center toView:self.mainView];
        _originalOutsidePosition = newLoc;
		[self removeFromSuperview];

        self.center = newLoc;
		[self.mainView addSubview:self];
        [self.mainView bringSubviewToFront:self];
		isInScrollview = NO;
	}
	else {
		;
	}

}


-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

	[UIView beginAnimations:@"stalk" context:nil];
	[UIView setAnimationDuration:.001];
	[UIView setAnimationBeginsFromCurrentState:YES];

	UITouch *touch = [touches anyObject];
	self.center = [touch locationInView: self.superview];
	[UIView commitAnimations];
}

-(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    if (![self.delegate checkConflictWithOtherButton:self inView:self.scrollParent]) {
        [UIView beginAnimations:@"goback" context:nil];
        [UIView setAnimationDuration:0.4f];
        [UIView setAnimationBeginsFromCurrentState:YES];
        self.center = _originalOutsidePosition;
        [UIView setAnimationDelegate:self];
        [UIView setAnimationDidStopSelector: @selector(animationDidStop:finished:context:)];
        [UIView commitAnimations];
    }
    [self.delegate touchUp];

}

-(void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
    if ([animationID isEqualToString:@"goback"] && finished) {
        [self removeFromSuperview];
        self.center = _originalPosition;
        [self.scrollParent addSubview:self];
        isInScrollview = YES;
    }
}



@end
